import { Component, Input } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { TallyCheckService } from '../../tally-check.service';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { AuthDictService } from '../../../../../system/dict/service/dict.service';
import { environment } from '@env/environment';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.less']
})
export class TallyCheckOstEditComponent {
	@Input()
	record;

	dataForm: FormGroup;
	checkTypeList: any;

	constructor(
		private fb: FormBuilder,
		private tallyCheckService: TallyCheckService,
		private modalRef: NzModalRef,
		private dictService: AuthDictService,
	) {
		this.dataForm = this.fb.group({
			checkPiece: [null, [Validators.required]],
			checkTon: [null, [Validators.required]],
			checkType: [null, [Validators.required]],
			checkReason: [null],
		});
		this.dictService.dictionary(environment.dict.CHECK_TYPE, 1).subscribe(res => {
			this.checkTypeList = res;
		});
	}

	ngOnInit(): void {
		if (this.record) {
			this.dataForm.patchValue(this.record);
		}
	}

	checkChange(): void {
		const isValid = this.validate();
		if (!isValid) {
			return;
		}
		const postData = {
			id: this.record.id,
			...this.dataForm.value,
		};
		this.tallyCheckService.ostCorrectPieceTon(postData).subscribe(() => {
			this.close();
		});
	}

	validate(): any {
		for (const key in this.dataForm.controls) {
			// eslint-disable-next-line no-prototype-builtins
			if (this.dataForm.controls.hasOwnProperty(key)) {
				const element = this.dataForm.controls[key];
				element.markAsDirty();
				element.updateValueAndValidity();
			}
		}
		return this.dataForm.valid;
	}

	close(): void {
		this.modalRef.close(true);
	}
}
